﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace Pawn
{
    public partial class VNDTextBox : TextBox
    {
        public new String Text
        {
            get
            {
                if (base.Text.Length == 0) return "0";
                return base.Text.Trim();
            }
            set
            {
                try
                {
                    value = value.Replace(" ", "").Trim();
                    value = Convert.ToInt64(value).ToString();
                    string s = "";
                    
                    for (int i = value.Length - 1; i >= 0; i--)
                    {
                        if ((value.Length - i) % 3 == 0 && i!=0)
                            s = String.Format(" {0}{1}", value[i], s);
                        else
                            s = value[i] + s;
                    }
                base.Text = s;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
                
            }
        }
        public Int64 Value
        {
            get{
                return Convert.ToInt64(this.Text.Replace(" ",""));
            }
            set
            {
                this.Text = value.ToString();
            }
        }
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
            char c = e.KeyChar;
            if (!(Char.IsControl(c) || Char.IsDigit(c))) return;
            base.OnKeyPress(e);
        }
        protected override void OnKeyUp(KeyEventArgs e)
        {
            if (base.Text.Length != 0)
            {
                int p = this.SelectionStart;
                int l = base.Text.Length;
                this.Text = base.Text;
                this.SelectionStart = this.Text.Length <= p ? this.Text.Length : this.Text.Length + p - l;
            }
            base.OnKeyUp(e);
        }
        protected override void OnLeave(EventArgs e)
        {
            if (base.Text.Length == 0) base.Text = "0";
            base.OnLeave(e);
        }

    }
}
